/**
 * Copyright (c) OpenSpug Organization. https://github.com/openspug/spug
 * Copyright (c) <spug.dev@gmail.com>
 * Released under the AGPL-3.0 License.
 */
import React from 'react';
import { observer } from 'mobx-react';
import { Modal, Form, Input, message } from 'antd';
import http from 'libs/http';
import store from './store';
import {CreateUser, UpdateUser} from "../../../api/system/account/UserApi";

@observer
class ComForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false
    }
  }

  handleSubmit = () => {
    this.setState({loading: true});
    const formData = this.props.form.getFieldsValue();
    CreateUser(formData).then(response => {
      if (response.data.code === 200){
        message.success("用户添加成功");
        store.fetchRecords();
        store.formVisible = false;
      }
    }).finally(() => this.setState({loading: false}));
  };

  render() {
    const info = store.record;
    const {getFieldDecorator} = this.props.form;
    return (
      <Modal
        visible
        width={800}
        maskClosable={false}
        title={store.record.id ? '编辑账户' : '新建账户'}
        onCancel={() => store.formVisible = false}
        confirmLoading={this.state.loading}
        onOk={this.handleSubmit}>
        <Form labelCol={{span: 6}} wrapperCol={{span: 14}}>
          <Form.Item required label="登录名">
            {getFieldDecorator('username', {initialValue: info['username']})(
              <Input placeholder="请输入登录名"/>
            )}
          </Form.Item>
          <Form.Item required label="昵称">
            {getFieldDecorator('nickname', {initialValue: info['nickname']})(
              <Input placeholder="请输入昵称"/>
            )}
          </Form.Item>
          <Form.Item required label="密码">
            {getFieldDecorator('password')(
                <Input type="password" placeholder="请输入密码"/>
            )}
          </Form.Item>
        </Form>
      </Modal>
    )
  }
}

export default Form.create()(ComForm)
